<template>
  <el-dialog
    :title="pageTitle"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :visible.sync="visible"
    lock-scroll
    append-to-body
    class="wpwork-dialog wpwork-dialog_center transfer-dialog"
    width="1000px"
  >
    <div class="transfer__body" v-loading="allLoading">
      <!-- 左侧面板：用户选择 -->
      <div class="transfer-pane">
        <div class="transfer-pane__tools">
          <el-input
            placeholder="请输入关键词查询"
            v-model="keyword"
            @keyup.enter.native="search"
            clearable
            class="search-input"
          >
            <el-button slot="append" icon="el-icon-search" @click="search"></el-button>
          </el-input>
        </div>
        <div class="transfer-pane__body left-pane">
          <!-- 用户表格 -->
          <el-table
            ref="userTable"
            :data="userList"
            tooltip-effect="dark"
            style="width: 100%"
            :row-class-name="getRowClass"
            v-loading="loading"
            @row-click="handleRowClick"
          >
          <!-- 隐藏多选框列，改用点击整行 -->
          <el-table-column type="index" width="55"></el-table-column>
          <el-table-column prop="account" label="账号" width="150"></el-table-column>
          <el-table-column prop="realName" label="姓名" width="140"></el-table-column>
          <el-table-column label="状态" width="100">
            <template slot-scope="scope">
              <!-- 区分：原绑定 / 本次新增 -->
              <el-tag
                size="mini"
                :type="getTagType(scope.row)"
                v-if="isBoundOrNew(scope.row)"
              >
                {{ getTagText(scope.row) }}
              </el-tag>
            </template>
          </el-table-column>
          </el-table>

          <!-- 分页 -->
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pagination.currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pagination.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total"
            class="pagination-container"
          ></el-pagination>
        </div>
      </div>

      <!-- 右侧面板：已绑定用户 -->
      <div class="transfer-pane">
        <div class="transfer-pane__tools">
          <span>已绑定用户</span>
          <el-button @click="removeAll" type="text" class="removeAllBtn">清空列表</el-button>
        </div>
        <div class="transfer-pane__body shadow right-pane">
          <template v-if="selectedData.length">
            <div
              v-for="item in selectedData"
              :key="item.id"
              class="selected-item-user"
            >
              <div
                class="selected-item-main"
                :class="{ 'new-binding': isAddedInThisSession(item.id) }"
              >
                <el-avatar
                  :size="36"
                  :src="define.comUrl + item.headIcon"
                  class="selected-item-headIcon"
                  :class="{ 'grayscale': !isAddedInThisSession(item.id) }"
                ></el-avatar>
                <div class="selected-item-text">
                  <p class="name">{{ item.realName }}</p>
                  <el-tag
                    size="mini"
                    type="success"
                    v-if="isAddedInThisSession(item.id)"
                  >新增</el-tag>
                </div>
                <i class="el-icon-delete" @click.stop="removeData(item.id)"></i>
              </div>
            </div>
          </template>
          <el-empty description="暂无绑定用户" :image-size="120" v-else></el-empty>
        </div>
      </div>
    </div>

    <!-- 底部按钮 -->
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">{{ $t('common.cancelButton') }}</el-button>
      <el-button type="primary" :loading="btnLoading" @click="dataFormSubmit()">
        {{ $t('common.confirmButton') }}
      </el-button>
    </span>
  </el-dialog>
</template>

<script>
import { getGroupUsers, bindUsers, unbindUsers, redisPush } from '@/api/group'
import { getUserInfoList, getUserList } from '@/api/permission/user'

export default {
  data() {
    return {
      visible: false,
      loading: false,
      btnLoading: false,
      allLoading: false,
      pageTitle: '',
      groupId: '',
      groupName: '',
      userList: [], // 当前页用户列表
      selectedData: [], // 所有已选用户（跨页）
      originalBoundUserIds: [], // 初始化时就已经绑定的用户 ID 列表（用于对比）
      keyword: '',
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      define: {
        comUrl: process.env.VUE_APP_CDN // 头像 CDN 地址
      }
    }
  },

  methods: {
    /**
     * 对外暴露的初始化方法
     * @param {string} groupId - 分组 ID
     * @param {string} groupName - 分组名称
     */
    async init(groupId, groupName) {
      this.visible = true
      this.groupId = groupId
      this.groupName = groupName
      this.pageTitle = '绑定用户 - ' + groupName

      // 重置状态
      this.userList = []
      this.selectedData = []
      this.originalBoundUserIds = []
      this.keyword = ''
      this.pagination.currentPage = 1

      this.allLoading = true

      try {
        // 并行加载：已绑定用户 + 第一页用户列表
        await Promise.all([
          this.loadBoundUsers(),
          this.initData()
        ])
      } catch (error) {
        console.error('初始化失败:', error)
        this.$message.error('初始化失败')
      } finally {
        this.allLoading = false
      }
    },

    /**
     * 加载已绑定的用户（从后端获取）
     */
    async loadBoundUsers() {
      try {
        const response = await getGroupUsers(this.groupId)
        if (response.code === 200) {
          const userIds = response.data || []
          this.originalBoundUserIds = [...userIds] // 保存原始绑定列表
          if (userIds.length > 0) {
            await this.getUserDetails(userIds)
          }
        } else {
          this.$message.error(response.msg || '获取已绑定用户失败')
        }
      } catch (error) {
        console.error('加载已绑定用户失败:', error)
        this.$message.error('获取已绑定用户失败')
      }
    },

    /**
     * 根据用户 ID 获取详细信息
     * @param {Array} userIds - 用户 ID 数组
     */
    async getUserDetails(userIds) {
      try {
        const response = await getUserInfoList(userIds)
        if (response.code === 200) {
          this.selectedData = response.data.list || []
        } else {
          this.$message.error(response.msg || '获取用户详情失败')
        }
      } catch (error) {
        console.error('获取用户详情失败:', error)
        this.$message.error('获取用户详情失败')
      }
    },

    /**
     * 搜索用户
     */
    search() {
      this.pagination.currentPage = 1
      this.initData()
    },

    /**
     * 初始化左侧用户列表（分页加载）
     */
    async initData() {
      this.loading = true
      try {
        const params = {
          keyword: this.keyword,
          currentPage: this.pagination.currentPage,
          pageSize: this.pagination.pageSize
        }
        const response = await getUserList(params)
        if (response.code === 200) {
          this.userList = response.data.list || []
          this.pagination.total = response.data.pagination.total

          // ✅ 初始化表格选中状态（必须在 DOM 更新后）
          this.$nextTick(() => {
            this.setTableSelection()
          })
        } else {
          this.$message.error(response.msg || '获取用户列表失败')
        }
      } catch (error) {
        console.error('获取用户列表失败:', error)
        this.$message.error('获取用户列表失败')
      } finally {
        this.loading = false
      }
    },

    /**
     * 设置表格的选中状态（基于 selectedData）
     */
    setTableSelection() {
      // 不需要手动设置选中样式，因为我们用的是 click 事件
      // 但我们可以加个 class 来表示是否在 selectedData 中
    },

    /**
     * 表格行点击事件（替代勾选）
     * @param {Object} row - 当前行数据
     */
    handleRowClick(row) {
      const exists = this.selectedData.some(selected => selected.id === row.id)

      if (exists) {
        // 已存在则移除（取消选中）
        this.removeData(row.id)
      } else {
        // 不存在则添加
        this.selectedData.push({
          id: row.id,
          realName: row.realName,
          headIcon: row.headIcon,
          account: row.account
        })
      }

      // 视觉反馈更新
      this.$forceUpdate()
    },

    /**
     * 获取行的 class 名称（用于高亮）
     * @param {Object} param - { row, rowIndex }
     */
    getRowClass({ row }) {
      const isSelected = this.selectedData.some(selected => selected.id === row.id)
      return isSelected ? 'table-row-selected' : ''
    },

    /**
     * 获取 tag 类型（用于状态标签）
     * @param {Object} row - 表格行
     */
    getTagType(row) {
      if (this.isAddedInThisSession(row.id)) return 'success'
      if (this.originalBoundUserIds.includes(row.id)) return 'info'
      return ''
    },

    /**
     * 获取 tag 显示文本
     * @param {Object} row - 表格行
     */
    getTagText(row) {
      if (this.isAddedInThisSession(row.id)) return '新增'
      if (this.originalBoundUserIds.includes(row.id)) return '已绑定'
      return ''
    },

    /**
     * 判断该用户是否是“原绑定”或“本次新增”
     * @param {Object} row - 表格行
     * @returns {Boolean}
     */
    isBoundOrNew(row) {
      return (
        this.originalBoundUserIds.includes(row.id) ||
        this.isAddedInThisSession(row.id)
      )
    },

    /**
     * 判断该用户是否是本次会话中新增的
     * @param {String} userId - 用户 ID
     * @returns {Boolean}
     */
    isAddedInThisSession(userId) {
      return (
        !this.originalBoundUserIds.includes(userId) &&
        this.selectedData.some(item => item.id === userId)
      )
    },

    /**
     * 分页大小变化
     * @param {Number} val - 新的页大小
     */
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.pagination.currentPage = 1
      this.initData()
    },

    /**
     * 当前页码变化
     * @param {Number} val - 新的页码
     */
    handleCurrentChange(val) {
      this.pagination.currentPage = val
      this.initData()
    },

    /**
     * 清空所有已绑定用户
     */
    removeAll() {
      this.$confirm('确定清空所有已绑定用户吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.selectedData = []
        this.$forceUpdate() // 强制刷新视图
      }).catch(() => {
        // 取消
      })
    },

    /**
     * 移除单个用户
     * @param {String} userId - 用户 ID
     */
    removeData(userId) {
      const index = this.selectedData.findIndex(item => item.id === userId)
      if (index !== -1) {
        this.selectedData.splice(index, 1)
      }

      // 强制刷新视图
      this.$forceUpdate()
    },

    /**
     * 提交绑定
     */
    async dataFormSubmit() {
      this.btnLoading = true
      try {
        const selectedUserIds = this.selectedData.map(item => item.id)

        // 获取当前已绑定的用户 ID（服务端最新状态）
        const currentRes = await getGroupUsers(this.groupId)
        const currentUserIds = currentRes.data || []

        // 计算差异
        const toBind = selectedUserIds.filter(id => !currentUserIds.includes(id))
        const toUnbind = currentUserIds.filter(id => !selectedUserIds.includes(id))

        // 执行绑定
        if (toBind.length > 0) {
          const bindRes = await bindUsers(this.groupId, toBind)
          if (bindRes.code !== 200) {
            throw new Error(bindRes.msg || '绑定用户失败')
          }
        }

        // 执行解绑
        if (toUnbind.length > 0) {
          const unbindRes = await unbindUsers(this.groupId, toUnbind)
          if (unbindRes.code !== 200) {
            throw new Error(unbindRes.msg || '解绑用户失败')
          }
        }

        // Redis 推送（可选）
        try {
          await redisPush()
        } catch (redisError) {
          console.warn('Redis推送失败:', redisError)
        }

        this.$message({
          message: '绑定用户成功',
          type: 'success',
          duration: 1500,
          onClose: () => {
            this.visible = false
            this.btnLoading = false
            this.$emit('success') // 通知父组件刷新
          }
        })

      } catch (error) {
        console.error('绑定失败:', error)
        this.$message.error(error.message || '绑定用户失败')
        this.btnLoading = false
      }
    }
  }
}
</script>

<style scoped>
.transfer__body {
  display: flex;
  height: 500px;
}

.transfer-pane {
  flex: 1;
  display: flex;
  flex-direction: column;
  margin: 0 10px;
}

.transfer-pane__tools {
  padding: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.transfer-pane__body {
  flex: 1;
  overflow: auto;
  padding: 10px;
}

/* 表格行点击样式 */
::v-deep .el-table tbody tr:hover td {
  cursor: pointer;
}

::v-deep .table-row-selected {
  background-color: #f0f9eb !important;
}

/* 右侧已绑定用户项 */
.selected-item-user {
  margin-bottom: 8px;
}

.selected-item-main {
  display: flex;
  align-items: center;
  padding: 8px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #f9f9f9;
  position: relative;
}



.selected-item-headIcon {
  margin-right: 10px;
}

.selected-item-headIcon.grayscale {
  filter: grayscale(80%);
}

.selected-item-text {
  flex: 1;
}

.selected-item-text .name {
  margin: 5px;
  font-weight: 500;
  color: #303133;
}

.el-icon-delete {
  color: #f56c6c;
  cursor: pointer;
  font-size: 16px;
}

.el-icon-delete:hover {
  color: #f78989;
}

.pagination-container {
  margin-top: 10px;
  text-align: right;
}
</style>
